package com.chant.startFarming.controller;

import com.chant.startFarming.dto.Result;
import com.chant.startFarming.entity.Menus;
import com.chant.startFarming.service.IMenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统菜单表 前端控制器
 */
@RestController
@RequestMapping("/menus")
public class MenusController {

    @Autowired
    private IMenusService menusService;

    // 查询所有菜单
    @GetMapping
    public Result getAllMenus() {
        List<Menus> menusList = menusService.list();
        List<Menus> parentMenus = new ArrayList<>();
        for (Menus menu : menusList) {
            if (menu.getParentId() == 0) {
                menu.setChildren(getChildren(menu.getId(), menusList));
                parentMenus.add(menu);
            }
        }
        return Result.ok(parentMenus, (long) parentMenus.size());
    }

    private List<Menus> getChildren(Integer parentId, List<Menus> menusList) {
        List<Menus> children = new ArrayList<>();
        for (Menus menu : menusList) {
            if (menu.getParentId().equals(parentId)) {
                menu.setChildren(getChildren(menu.getId(), menusList));
                children.add(menu);
            }
        }
        return children;
    }


    // 根据ID查询菜单
    @GetMapping("/{id}")
    public Result getMenuById(@PathVariable Integer id) {
        Menus menu = menusService.getById(id);
        if (menu == null) {
            return Result.fail("菜单不存在");
        }
        return Result.ok(menu);
    }

    // 新增菜单
    @PostMapping
    public Result createMenu(@RequestBody Menus menu) {
        menu.setCreatedAt(LocalDateTime.now());
        menu.setUpdatedAt(LocalDateTime.now());
        boolean isSaved = menusService.save(menu);
        return isSaved ? Result.ok() : Result.fail("新增失败");
    }

    // 修改菜单
    @PutMapping("/{id}")
    public Result updateMenu(@PathVariable Integer id, @RequestBody Menus menu) {
        menu.setId(id); // 确保ID一致性
        menu.setUpdatedAt(LocalDateTime.now());
        boolean isUpdated = menusService.updateById(menu);
        return isUpdated ? Result.ok() : Result.fail("更新失败");
    }

    // 删除菜单
    @DeleteMapping("/{id}")
    public Result deleteMenu(@PathVariable Integer id) {
        boolean isRemoved = menusService.removeById(id);
        return isRemoved ? Result.ok() : Result.fail("删除失败");
    }


    @GetMapping("/role/{role}")
    public Result getMenusByRole(@PathVariable Integer role) {
        List<Menus> menus = menusService.getMenusByRole(role);
        return Result.ok(menus);
    }


}